package com.graduate.examapp.service

import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.os.Build
import android.provider.AlarmClock
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.graduate.examapp.R
import com.graduate.examapp.broadcast.AlarmBroadcastReciever
import com.graduate.examapp.entity.ExamTask
import com.graduate.examapp.view.activity.MainActivity
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId

class UserNotice(
    private val context: Context
) {
    //设置 通知兰提醒
    fun setExamTaskNotification(noticeMessage: String) {
        Log.d("UserNotice", "通知栏")
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            Intent(context, MainActivity::class.java),
            PendingIntent.FLAG_IMMUTABLE
        )
        createNotificationChannel()
        val notification = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.drawable.icon_notice_black_32)
            .setContentTitle("ExamApp")
            .setContentText(noticeMessage)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent) //点击跳转主页面
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .build()
        NotificationManagerCompat.from(context)
            .notify(1, notification)
    }


    //设置闹钟
    fun setAlarm(examTask: ExamTask) {
        Log.d("UserNotice", "闹钟")
        val examDateTime = parseAlarmTime(examTask)
        val stringBuilder = StringBuilder()
        stringBuilder.append("监考信息\n")
            .append("半小时后\n")
            .append(examTask.place)
            .append("\n")
            .append(examTask.courseName)
        /**
         * 如果要设置多个报警(重复或单个)，则只需要使用不同的requestCode创建它们的PendingIntents。如果requestCode相同，则新的报警将覆盖旧报警。
         */
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val milli = examDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
        //设置闹钟广播 intent
        val intent = Intent(context, AlarmBroadcastReciever::class.java)
        intent.putExtra("alarm_message", stringBuilder.toString())
        val pendingIntent = PendingIntent.getBroadcast(context, examTask.id, intent, PendingIntent.FLAG_IMMUTABLE)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, milli, pendingIntent)
    }


    private fun parseAlarmTime(examTask: ExamTask): LocalDateTime {
        val examDate = examTask.examDate

        val examStartTime = examTask.duration.split("-")[0]

        val examStartHourAndMin = examStartTime.split(":")

        val hour = examStartHourAndMin[0].toInt()

        val min = examStartHourAndMin[1].toInt()

        val examDateTime = LocalDateTime.of(examDate, LocalTime.of(hour, min))

        //设置为提前半个小时闹钟响铃
        return examDateTime.minusMinutes(30)
    }


    // 取消闹钟
    fun dismissAlarm(examTask: ExamTask) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        //设置闹钟广播 intent
        val intent = Intent(context, AlarmBroadcastReciever::class.java)
        val pendingIntent = PendingIntent.getBroadcast(context, examTask.id, intent, PendingIntent.FLAG_IMMUTABLE)
        alarmManager.cancel(pendingIntent)
    }


    private fun createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val descriptionText = "channel"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, "exam_task", importance).apply {
                description = descriptionText
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    companion object {
        const val CHANNEL_ID: String = "1"
    }
}